<template>
  <div class="app-container">
    <h2>运费设置</h2>

    <!-- Tab 切换 -->
    <el-tabs v-model="this.rulesForm.type" @tab-click="handleTabChange">
      <el-tab-pane label="商品订单" name="1"></el-tab-pane>
      <el-tab-pane label="云仓自提订单" name="2"></el-tab-pane>
    </el-tabs>

    <!-- 运费规则表单 -->
    <el-form :model="rulesForm" label-width="130px">
      <el-form-item label="商品类型" v-if="rulesForm.type === '1'">
        <span>单品</span>
      </el-form-item>

      <!-- 区间配置 -->
      <el-form-item label="订单支付总额区间">
        <div
          v-for="(item, index) in rulesForm.rules"
          :key="index"
          style="display:flex; align-items:center; margin-bottom:15px; gap:15px;"
        >
          <!-- 起始金额 -->
          <el-input v-model="item.startPrice" style="width:120px" /> <span>元</span>

          <span>——</span>

          <!-- 结束金额 -->
          <el-input v-model="item.endPrice" style="width:120px" /> <span>元</span>

          <span>运费</span>

          <!-- 运费 -->
          <el-input v-model="item.price" style="width:120px" /> <span>元</span>

          <!-- 添加/删除按钮 -->
          <el-button type="primary" icon="el-icon-plus" circle size="mini" @click="addRule(index)" />
          <el-button v-if="rulesForm.rules.length > 1" type="danger" icon="el-icon-minus" circle size="mini" @click="removeRule(index)" />
        </div>

      </el-form-item>
    </el-form>

    <!-- 提交按钮 -->
    <div style="margin-top:20px;">
      <el-button type="primary" @click="saveRules">保存</el-button>
    </div>
  </div>
</template>

<script>
import { listCost, saveCost } from "@/api/system/cost";

export default {
  name: "FreightSetting",
  data() {
    return {
      // activeType: "1", // 默认商品订单
      rulesForm: {
        type: "1", // 1:商品订单 2:云仓
        rules: [
        ]
      }
    }
  },
  created() {
    this.getRules();
  },
  methods: {
    // 切换 tab
    handleTabChange(tab) {
      this.rulesForm.type = tab.name;
      this.getRules();
    },
    // 获取运费规则
    getRules() {
      listCost({ type: this.rulesForm.type }).then(res => {
        if (res.rows && res.rows.length > 0) {
          this.rulesForm.rules = res.rows.map(item => ({
            startPrice: item.startPrice,
            endPrice: item.endPrice,
            price: item.price
          }));
        } else {
          this.rulesForm.rules = [{ startPrice: null, endPrice: null, price: null }];
        }
      });
    },
    // 添加区间
    addRule(index) {
      this.rulesForm.rules.splice(index + 1, 0, { startPrice: "", endPrice: "", price: "" });
    },
    // 删除区间
    removeRule(index) {
      this.rulesForm.rules.splice(index, 1);
    },
    // 保存
    saveRules() {
      saveCost(this.rulesForm).then(res => {
        if (res.code === 200) {
          this.$message.success("保存成功");
        }
      })
    }
  }
};
</script>
